package com.zkthink.ceres.common.utils;

import cn.hutool.core.codec.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QcodeUtil {
    public String createQRCode(String content, int width, int height) throws IOException {
        String resultImage = "";
        if (!content.isEmpty()) {
            ServletOutputStream stream = null;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            @SuppressWarnings("rawtypes")
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//指定字符编码为“utf-8”
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//指定二维码的纠错等级为中
            hints.put(EncodeHintType.MARGIN, 2);//指定二维码边距
            try {

                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
                MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
//                BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//                for (int x = 0; x < width; x++) {
//                    for (int y = 0; y < height; y++) {
//                        bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
//                    }
//                }
                Graphics2D g2 = bufferedImage.createGraphics();
                g2.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
//                g2.draw(new RoundRectangle2D.Float(width / 5 * 2, height / 5 * 2, width / 5, height / 5, 20, 20));
                g2.dispose();
                g2.setColor(Color.white);
                g2.setBackground(Color.white);
                bufferedImage.flush();
                ImageIO.write(bufferedImage, "png", os);
                //OutputStream out = new FileOutputStream("D:\\logo\\abb.png"); //转码前保存图片文件到指定目录
                //out.write(os.toByteArray());
                resultImage = new String("data:image/png;base64," + Base64.encode(os.toByteArray()));
                return resultImage;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
        return null;
    }


    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 仅生成二维码，返回二维码图片网络地址，可直接扫码访问
     *
     * @param address：扫码地址
     * @return
     */
    public static void getQRCode(String content, String relativePath) {
        File file = new File(relativePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        encode(content, file, "png", BarcodeFormat.QR_CODE, 500, 500, null);

    }


    /**
     * 生成QRCode二维码<br>
     * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>
     * static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>
     * 修改为UTF-8，否则中文编译后解析不了<br>
     *
     * @param contents    二维码的内容
     * @param file        二维码保存的路径，如：C://test_QR_CODE.png
     * @param filePostfix 生成二维码图片的格式：png,jpeg,gif等格式
     * @param format      qrcode码的生成格式
     * @param width       图片宽度
     * @param height      图片高度
     * @param hints
     */
    public static void encode(String contents, File file, String filePostfix, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);
            writeToFile(bitMatrix, filePostfix, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码图片<br>
     *
     * @param matrix
     * @param format 图片格式
     * @param file   生成二维码图片位置
     * @throws IOException
     */
    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        ImageIO.write(image, format, file);
    }

    /**
     * 生成二维码内容<br>
     *
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }

//    /**
//     * 解析QRCode二维码
//     */
//    @SuppressWarnings("unchecked")
//    public static void decode(File file) {
//        try {
//            BufferedImage image;
//            try {
//                image = ImageIO.read(file);
//                if (image == null) {
//                    System.out.println("Could not decode image");
//                }
//                LuminanceSource source = new BufferedImageLuminanceSource(image);
//                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
//                Result result;
//                @SuppressWarnings("rawtypes")
//                Hashtable hints = new Hashtable();
//                //解码设置编码方式为：utf-8
//                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
//                result = new MultiFormatReader().decode(bitmap, hints);
//                String resultStr = result.getText();
//                System.out.println("解析后内容：" + resultStr);
//            } catch (IOException ioe) {
//                System.out.println(ioe.toString());
//            } catch (ReaderException re) {
//                System.out.println(re.toString());
//            }
//        } catch (Exception ex) {
//            System.out.println(ex.toString());
//        }
//    }
}
